import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'

const routes = [
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/components/Layout.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { title: '首页' }
      },
        {
    path: '/resources',
    name: 'Resources',
    component: () => import('@/views/Resources.vue'),
    meta: { title: '学习资源' }
  },
        {
        path: '/resources/:id',
        name: 'ResourceDetail',
        component: () => import('@/views/ResourceDetail.vue'),
        meta: { title: '资源详情' }
      }

    ]
  },
  // 用户个人中心路由
  {
    path: '/user',
    component: () => import('@/components/UserLayout.vue'),
    redirect: '/user/profile',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/user/profile',
        name: 'UserProfile',
        component: () => import('@/views/user/Profile.vue'),
        meta: { title: '个人中心', requiresAuth: true }
      },
      {
        path: '/user/favorites',
        name: 'UserFavorites',
        component: () => import('@/views/user/Favorites.vue'),
        meta: { title: '我的收藏', requiresAuth: true }
      },
      {
        path: '/user/settings',
        name: 'UserSettings',
        component: () => import('@/views/user/Settings.vue'),
        meta: { title: '账号设置', requiresAuth: true }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '用户登录', hideNavbar: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '用户注册', hideNavbar: true }
  },
  // 管理员初始化路由
  {
    path: '/init',
    name: 'InitAdmin',
    component: () => import('@/views/admin/InitAdmin.vue'),
    meta: { title: '初始化管理员', hideNavbar: true }
  },
  // 管理员登录重定向
  {
    path: '/admin',
    redirect: '/admin-login'
  },
  // 管理员登录路由
  {
    path: '/admin-login',
    name: 'AdminLogin',
    component: () => import('@/views/admin/AdminLogin.vue'),
    meta: { title: '管理员登录', hideNavbar: true }
  },
  // 管理员后台路由
  {
    path: '/admin-panel',
    component: () => import('@/components/AdminLayout.vue'),
    redirect: '/admin-panel/dashboard',
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: '/admin-panel/dashboard',
        name: 'AdminDashboard',
        component: () => import('@/views/admin/Dashboard.vue'),
        meta: { title: '管理后台 - 仪表盘', requiresAuth: true, requiresAdmin: true }
      },
      {
        path: '/admin-panel/users',
        name: 'AdminUsers',
        component: () => import('@/views/admin/Users.vue'),
        meta: { title: '管理后台 - 用户管理', requiresAuth: true, requiresAdmin: true }
      },
      {
        path: '/admin-panel/resources',
        name: 'AdminResources',
        component: () => import('@/views/admin/Resources.vue'),
        meta: { title: '管理后台 - 资源管理', requiresAuth: true, requiresAdmin: true }
      },
      {
        path: '/admin-panel/comments',
        name: 'AdminComments',
        component: () => import('@/views/admin/Comments.vue'),
        meta: { title: '管理后台 - 评论管理', requiresAuth: true, requiresAdmin: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { title: '页面未找到' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 如果有保存的滚动位置（浏览器前进/后退），使用保存的位置
    if (savedPosition) {
      return savedPosition
    }
    // 如果有锚点，滚动到锚点
    if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth'
      }
    }
    // 否则滚动到页面顶部
    return { top: 0, behavior: 'smooth' }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    store.dispatch('setPageTitle', to.meta.title)
  }

  // 如果访问需要认证的页面但当前没有登录状态，尝试从localStorage恢复
  if (to.meta.requiresAuth && !store.getters.getLoginStatus) {
    try {
      const context = to.meta.requiresAdmin ? 'admin' : 'frontend'
      const initResult = await store.dispatch('initializeUser', context)
      
      if (initResult.success) {
        console.log(`成功恢复${context === 'admin' ? '管理员' : '用户'}登录状态`)
      }
    } catch (error) {
      console.error('恢复登录状态失败:', error)
    }
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const isLoggedIn = store.getters.getLoginStatus
    if (!isLoggedIn) {
      // 如果是管理员页面，重定向到管理员登录
      if (to.meta.requiresAdmin) {
        next({ path: '/admin-login' })
      } else {
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
      }
      return
    }
  }

  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin) {
    const userInfo = store.state.userInfo
    if (!userInfo || (userInfo.role !== 'ADMIN' && userInfo.userRole !== 'ADMIN')) {
      next({ path: '/admin-login' })
      return
    }
  }

  // 如果已登录用户访问登录/注册页面，重定向到首页
  if ((to.name === 'Login' || to.name === 'Register') && store.getters.getLoginStatus) {
    next({ path: '/home' })
    return
  }

  // 如果已登录管理员访问管理员登录页面，重定向到管理后台
  if (to.name === 'AdminLogin' && store.getters.getLoginStatus) {
    const userInfo = store.state.userInfo
    if (userInfo && (userInfo.role === 'ADMIN' || userInfo.userRole === 'ADMIN')) {
      next({ path: '/admin-panel/dashboard' })
      return
    }
  }

  next()
})

export default router
